<template>
  <view class="container">
    <!-- 标题 -->
    <view class="header">
      <text class="title">播放历史</text>
      <view class="clear-history" v-if="history.length > 0" @click="clearHistory">
        <text class="clear-text">清除历史</text>
      </view>
    </view>

    <!-- 历史记录列表 -->
    <view class="song-list-vertical" v-if="history.length > 0">
      <!-- 显示前3首歌曲 -->
      <view class="song-item-vertical" v-for="(song, index) in displaySongs" :key="song.song_id" @click="playSong(song, index)">
        <image class="song-cover-vertical" :src="song.cover_image_url" mode="aspectFill" />
        <view class="song-info-vertical">
          <text class="song-name-vertical">{{ song.name }}</text>
          <text class="song-artist-vertical">{{ song.artist_name }}</text>
          <text class="song-history">播放时间: {{ formatTime(song.play_time) }}</text>
        </view>
        <view class="song-play-btn">
          <text class="play-icon">▶️</text>
        </view>
      </view>
      
      <!-- 更多按钮 -->
      <view class="more-item" v-if="history.length > 3" @click="showAllHistory = !showAllHistory">
        <view class="more-content">
          <text class="more-text">{{ showAllHistory ? '收起' : `查看全部${history.length}首` }}</text>
          <text class="more-icon">{{ showAllHistory ? '▲' : '▼' }}</text>
        </view>
      </view>
    </view>

    <!-- 无历史记录提示 -->
    <view class="empty-tip" v-else>
      <text class="empty-text">暂无播放历史</text>
    </view>

    <!-- 底部播放器 -->
    <view class="mini-player" v-if="currentSong" @click="goToPlayer">
      <image class="mini-player-cover" :src="currentSong.cover_image_url" mode="aspectFill" />
      <view class="mini-player-info">
        <text class="mini-player-name">{{ currentSong.name }}</text>
        <text class="mini-player-artist">{{ currentSong.artist_name }}</text>
      </view>
      <view class="mini-player-controls">
        <text class="control-btn" @click.stop="togglePlay">
          {{ isPlaying ? '⏸️' : '▶️' }}
        </text>
        <text class="control-btn" @click.stop="nextSong">⏭️</text>
      </view>
    </view>
  </view>
</template>

<script>
// 内联API配置以避免模块导入问题
const BASE_URL = 'http://localhost:3000/api'

function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 导入音乐播放器
import musicPlayer from '/utils/musicPlayer.js'

const api = {
  music: {
    getHistory() {
      return request({
        url: '/music/history',
        method: 'GET'
      })
    },
    
    // 清除播放历史
    clearHistory() {
      return request({
        url: '/music/history',
        method: 'DELETE'
      })
    },
    
    // 获取歌曲详情
    getSongDetail(songId) {
      return request({
        url: `/music/song/${songId}`,
        method: 'GET'
      })
    }
  }
}

export default {
  data() {
    return {
      history: [],
      currentSong: null,
      isPlaying: false,
      isLoading: false,  // 添加加载状态标志
      showAllHistory: false  // 控制是否显示全部历史记录
    }
  },

  computed: {
    // 计算属性：根据showAllHistory的值决定显示的歌曲列表
    displaySongs() {
      if (this.showAllHistory || this.history.length <= 3) {
        return this.history;
      } else {
        return this.history.slice(0, 3);
      }
    }
  },

  onShow() {
    if (!this.isLoading) {
      this.isLoading = true;
      this.loadHistory().finally(() => {
        this.isLoading = false;
      });
    }
  },

  methods: {
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
    },

    // 加载历史记录
    async loadHistory() {
      try {
        const response = await api.music.getHistory();
        // 使用Set去重，基于song_id
        const uniqueHistory = [...new Map(response.data.map(item => 
          [item.song_id, item])).values()];
        this.history = uniqueHistory || [];
      } catch (error) {
        console.error('加载历史记录失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
        throw error;
      }
    },

    // 播放歌曲
    async playSong(song, index) {
      // 获取歌曲详情（这会自动记录播放历史）
      try {
        const response = await api.music.getSongDetail(song.song_id);
        const songDetail = response.data || song;
        
        // 设置播放列表（使用历史记录列表）
        musicPlayer.setPlaylist(this.history, index);
        
        // 更新当前歌曲状态
        this.currentSong = songDetail;
        this.isPlaying = true;
      } catch (error) {
        console.error('获取歌曲详情失败:', error);
        uni.showToast({
          title: '播放失败',
          icon: 'none'
        });
      }
    },

    // 切换播放状态
    togglePlay() {
      musicPlayer.togglePlay();
      this.isPlaying = musicPlayer.getCurrentInfo().isPlaying;
    },

    // 下一首
    nextSong() {
      musicPlayer.next();
      const playerInfo = musicPlayer.getCurrentInfo();
      this.currentSong = playerInfo.song;
      this.isPlaying = playerInfo.isPlaying;
    },

    // 跳转到播放器页面
    goToPlayer() {
      uni.navigateTo({
        url: '/pages/player/player'
      });
    },
    
    // 清除播放历史
    async clearHistory() {
      try {
        // 确认对话框
        const confirmRes = await uni.showModal({
          title: '确认清除',
          content: '确定要清除所有播放历史吗？此操作不可恢复。',
          confirmColor: '#ff6b6b'
        });
        
        if (confirmRes.confirm) {
          const response = await api.music.clearHistory();
          if (response.code === 200) {
            this.history = [];
            this.showAllHistory = false;  // 重置显示状态
            uni.showToast({
              title: '历史记录已清除',
              icon: 'success'
            });
          } else {
            throw new Error(response.message || '清除失败');
          }
        }
      } catch (error) {
        console.error('清除播放历史失败:', error);
        uni.showToast({
          title: '清除失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.header {
  padding: 30rpx;
  text-align: center;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.clear-history {
  padding: 10rpx 20rpx;
  background-color: #ff6b6b;
  border-radius: 30rpx;
}

.clear-text {
  color: white;
  font-size: 24rpx;
}

.song-list-vertical {
  display: flex;
  flex-direction: column;
}

.song-item-vertical {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.song-cover-vertical {
  width: 100rpx;
  height: 100rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.song-info-vertical {
  flex: 1;
}

.song-name-vertical {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-artist-vertical {
  display: block;
  font-size: 24rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.song-history {
  display: block;
  font-size: 22rpx;
  color: #ccc;
  margin-top: 5rpx;
}

.song-play-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  border-radius: 30rpx;
}

.play-icon {
  font-size: 30rpx;
  color: #ff6b6b;
}

.more-item {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
  background-color: white;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.more-content {
  display: flex;
  align-items: center;
}

.more-text {
  font-size: 28rpx;
  color: #ff6b6b;
  margin-right: 10rpx;
}

.more-icon {
  font-size: 24rpx;
  color: #ff6b6b;
}

.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.mini-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: white;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.mini-player-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.mini-player-info {
  flex: 1;
}

.mini-player-name {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 5rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-artist {
  display: block;
  font-size: 22rpx;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.mini-player-controls {
  display: flex;
  align-items: center;
}

.control-btn {
  font-size: 40rpx;
  margin-left: 20rpx;
  padding: 10rpx;
}
</style>